package com.free.food.order.service.impl;

import com.free.food.core.enums.order.OrderStatusEnum;
import com.free.food.core.enums.order.PayStatusEnum;
import com.free.food.core.util.KeyUtil;
import com.free.food.order.domain.dto.OrderDTO;
import com.free.food.order.entity.OrderDetail;
import com.free.food.order.entity.OrderMaster;
import com.free.food.order.repository.OrderDetailRepository;
import com.free.food.order.repository.OrderMasterRepository;
import com.free.food.order.service.OrderService;
import com.free.food.product.client.ProductClient;
import com.free.food.product.req.DecreaseStockReq;
import com.free.food.product.res.FindProductInfoRes;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 类功能描述：
 *
 * @author：刘富国
 * @createTime：2019/2/14 11:16
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMasterRepository orderMasterRepository;
    @Autowired
    private OrderDetailRepository orderDetailRepository;
    @Autowired
    private ProductClient productClient;

    @Override
    public OrderDTO create(OrderDTO orderDTO) {

        String orderId = KeyUtil.getUniqueKey();
        //1. 查询商品信息（调用商品服务）
        List<String> productIdList = orderDTO.getOrderDetails().stream()
                .map(OrderDetail::getProductId)
                .collect(Collectors.toList());
        List<FindProductInfoRes> productInfoList = productClient.listForOrder(productIdList);

        //2. 计算总价
        BigDecimal totalAmount = new BigDecimal(BigInteger.ZERO);
        for (OrderDetail orderDetail : orderDTO.getOrderDetails()) {
            for (FindProductInfoRes productInfo : productInfoList) {
                if (orderDetail.getProductId().equals(productInfo.getProductId())) {
                    totalAmount = totalAmount.add(new BigDecimal(orderDetail.getProductQuantity())
                            .multiply(productInfo.getProductPrice()));
                    //订单详情入库
                    BeanUtils.copyProperties(productInfo, orderDetail);
                    orderDetail.setOrderId(orderId);
                    orderDetail.setDetailId(KeyUtil.getUniqueKey());
                    orderDetailRepository.save(orderDetail);
                }
            }
        }
        //3. 扣库存（调用商品服务）
        List<DecreaseStockReq> cartDTOList = orderDTO.getOrderDetails().stream()
                .map(e -> new DecreaseStockReq(e.getProductId(), e.getProductQuantity()))
                .collect(Collectors.toList());
        productClient.decreaseStock(cartDTOList);
        //4. 订单入库
        OrderMaster orderMaster = new OrderMaster();
        orderDTO.setOrderId(orderId);
        BeanUtils.copyProperties(orderDTO, orderMaster);
        orderMaster.setOrderAmount(totalAmount);
        orderMaster.setOrderStatus(OrderStatusEnum.NEW.getCode());
        orderMaster.setPayStatus(PayStatusEnum.WAIT.getCode());
        Timestamp currentTime = new Timestamp(System.currentTimeMillis());
        orderMaster.setCreateTime(currentTime);
        orderMaster.setUpdateTime(currentTime);
        orderMasterRepository.save(orderMaster);
        return orderDTO;
    }
}
